package com.zxd.interview.cocurrent;

import java.util.concurrent.*;

/**
 *
 * 源码来自：https://mp.weixin.qq.com/s/40I466No_txvSptYLkoDXg
 * 作用：
 * 1.  Executors.newSingleThreadExecutor(); 中存在的jdk的bug
 * 2.
 * @author zhaoxudong
 * @version v1.0.0
 * @Package : com.zxd.interview.cocurrent
 * @Description : 探究jdk中一个多线程的bug和线程回收问题
 * @Create on : 2022/1/11 13:11
 **/
public class ThreadPoolTest {

    /**
     * 总结方法验证
     * @description 总结方法验证
     * @param args 
     * @return void 
     * @author 赵小东
     * @date 2022/6/17 22:52
     */ 
    public static void main(String[] args) {
        final ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        // 创建8个线程
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                while (true) {
                    // 获取一个任务
                    Future<String> future = threadPoolTest.submit();
                    try {
                        String s = future.get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (Error e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        //子线程不停gc，模拟偶发的gc
        new Thread(() -> {
            while (true) {
                System.gc();
            }
        }).start();
    }

    /** 
     * 异步执行任务
     * @description 异步执行任务 
     * @param  
     * @return java.util.concurrent.Future<java.lang.String> 
     * @author 赵小东
     * @date 2022/6/17 22:52
     */ 
    public Future<String> submit() {
        //关键点，通过Executors.newSingleThreadExecutor创建一个单线程的线程池
        // PS：注意是单线程的线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        FutureTask<String> futureTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(50);
                return System.currentTimeMillis() + "";
            }
        });
        // 执行异步任务
        executorService.execute(futureTask);
        return futureTask;
    }
}
